package com.jirong.shop.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jirong.shop.pojo.TUser;
import com.jirong.shop.service.TUserService;
import com.jirong.shop.utils.CookieUtil;
import com.jirong.shop.vo.RespBean;
import com.jirong.shop.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

//组件
@Component
@Slf4j
public class AccessInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate redisTemplate;
    @Autowired
    private TUserService userService;

    //    执行之前的方法没有走拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        拦截的是方法
        TUser user = getUser(request, response);
        UserContext.setUser(user);
        if (handler instanceof HandlerMethod) {
            //            放入本地线程
            HandlerMethod hm = (HandlerMethod) handler;
//            拿到方法上的注解。。。
//            hm.getBean()//注入依赖获取。
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
//            System.out.println(accessLimit);
//            没有注解就不限流
            if (accessLimit == null) {
                return true;
            }
            int second = accessLimit.second();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
//返回全路径
            String key = request.getRequestURI();
//            判断用户
            if (needLogin) {
                if (user == null) {
//                    JSON工具返回前端
                    render(response, RespBeanEnum.SESSION_ERROR);
                    return false;
                }
//                (uri + ":" + user.getId()
                key += ":" + user.getId();
            }
//            用redis缓存加计数器实现限流后面换redis工具类，
//            值就为访问次数
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            if (count == null) {
                valueOperations.set(key, 1, second, TimeUnit.SECONDS);
            } else if (count < maxCount) {
                valueOperations.increment(key);
            } else {
                render(response, RespBeanEnum.ACCESS_LIMIT_REACHED);
                return false;
            }
        }
        System.out.println("***********拦截到了*************用这个测试拦截器");
        return true;
    }

    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        RespBean bean = RespBean.error(respBeanEnum);
//        javaweb传前端页面数据方法
        out.write(new ObjectMapper().writeValueAsString(bean));
        out.flush();
        out.close();
    }

    private TUser getUser(HttpServletRequest request, HttpServletResponse response) {
        String ticket = CookieUtil.getCookieValue(request, "ticketUser");
        if (StringUtils.isEmpty(ticket)) {
            return null;
        }
        return userService.getUserByCookie(ticket, request, response);
    }
}
